import sys  
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton, QLabel  
from PyQt5.QtGui import QPainter, QPen, QImage  
from PyQt5.QtCore import Qt, QPoint, QEvent  
  
class HandwrittenDigitRecognizer(QWidget):  
    def __init__(self):  
        super().__init__()  
        self.initUI()  
        self.drawing = False  
        self.last_point = QPoint()  
        self.image = QImage(self.size(), QImage.Format_RGB32)  
        self.image.fill(Qt.white)  
  
    def initUI(self):  
        self.setWindowTitle('手写数字识别系统')  
        self.setGeometry(300, 300, 500, 500)  
  
        # 创建垂直布局  
        vlayout = QVBoxLayout(self)  
  
        # 创建画布部件  
        self.canvas = QLabel(self)  
        self.canvas.setAlignment(Qt.AlignCenter)  
        vlayout.addWidget(self.canvas)  
  
        # 创建识别按钮并添加到布局的底部  
        self.recognize_button = QPushButton('识别数字', self)  
        self.recognize_button.clicked.connect(self.recognizeDigit)  
        vlayout.addWidget(self.recognize_button, alignment=Qt.AlignCenter)  
  
        # 设置画布鼠标事件  
        self.canvas.mousePressEvent = self.on_mouse_press  
        self.canvas.mouseMoveEvent = self.on_mouse_move  
        self.canvas.mouseReleaseEvent = self.on_mouse_release  
        self.canvas.paintEvent = self.on_paint_event  
  
    def on_mouse_press(self, event):  
        if event.button() == Qt.LeftButton:  
            self.drawing = True  
            self.last_point = event.pos()  
  
    def on_mouse_move(self, event):  
        if (event.buttons() & Qt.LeftButton) and self.drawing:  
            painter = QPainter(self.image)  
            painter.setPen(QPen(Qt.black, 2, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))  
            painter.drawLine(self.last_point, event.pos())  
            self.last_point = event.pos()  
            painter.end()  
            self.canvas.update()  
  
    def on_mouse_release(self, event):  
        if event.button() == Qt.LeftButton:  
            self.drawing = False  
  
    def on_paint_event(self, event):  
        painter = QPainter(self.canvas)  
        painter.drawImage(0, 0, self.image)  
  
    def recognizeDigit(self):  
        # TODO: 在这里调用数字识别模型进行预测，并显示结果  
        print("正在识别数字...")  
  
if __name__ == '__main__':  
    app = QApplication(sys.argv)  
    ex = HandwrittenDigitRecognizer()  
    ex.show()  
    sys.exit(app.exec_())